package com.signcomplex.nettyandroid;

import android.os.Handler;
import android.os.Message;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class TimeClientHandler extends ChannelInboundHandlerAdapter {

    private ChannelHandlerContext channelHandlerContext = null;
    private boolean isConnect = false;

    public boolean isConnect() {
        return isConnect;
    }

    private static TimeClientHandler instance;

    public static TimeClientHandler getInstance() {
        // 直接获取内部类的变量
        return instance;
    }

    public ChannelHandlerContext getChannelHandlerContext() {
        return channelHandlerContext;
    }

    private Handler handler;

    /**
     * Creates a client-side handler.
     */
    public TimeClientHandler(Handler handler) {
        LogUtil.i("TimeClientHandler-->构造方法");
        instance = this;
        this.handler = handler;
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        LogUtil.i("TimeClientHandler channelInactive-->");
        if (handler != null) {
            Message message = new Message();
            message.what = RequestCode.REQUEST_CODE_RECONNECT;
            message.obj = "Reconnect";
            handler.sendMessage(message);
        }
//        final EventLoop eventLoop = ctx.channel().eventLoop();
//        eventLoop.schedule(new Runnable() {
//
//            @Override
//            public void run() {
//                LogUtil.i("channelInactive run-->");
//            }
//
//        }, 1, TimeUnit.SECONDS);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // TODO Auto-generated method stub
        LogUtil.i("TimeClientHandler channelActive-->");

        isConnect = true;
        channelHandlerContext = ctx;

        StringBuffer sb = new StringBuffer("");
        sb.append("Connect");

        String str = new String(sb);
        LogUtil.i("client send-->" + str);

        byte[] req = ByteUtil.assembly(str.getBytes(RequestCode.CHARSET_NAME), RequestCode.REQUEST_CODE_CONNECT);

        ByteBuf firstMessage = Unpooled.buffer(req.length);
        firstMessage.writeBytes(req);
        ctx.writeAndFlush(firstMessage);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // TODO Auto-generated method stub
        LogUtil.i("TimeClientHandler channelRead-->");

        ByteBuf buf = (ByteBuf) msg;
        byte[] req = new byte[buf.readableBytes()];
        buf.readBytes(req);
        String body = new String(req, RequestCode.CHARSET_NAME);
//        LogUtil.i("TimeClientHandler req-->" + req.length);
        LogUtil.i("client receive-->" + body);

        if (handler != null) {
            Message message = new Message();
            message.what = req[0];
            message.obj = new String(ByteUtil.assembly(req), RequestCode.CHARSET_NAME);
            handler.sendMessage(message);
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        LogUtil.i("TimeClientHandler channelReadComplete-->");

        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // TODO Auto-generated method stub
        LogUtil.i("TimeClientHandler exceptionCaught-->" + cause.getMessage());

        // 释放资源
        ctx.close();
    }

}
